<template>
    <div class="snow-page">
        <a-layout>
            <a-layout-sider style="height: 100vh;">
                <div>
                    <h3 style="margin-top: 10px;margin: 6px;">设置列表</h3>
                    <a-tree :data="deviceLost" :default-selected-keys="[41]" :field-names="{
                        key: 'id',
                        title: 'name',
                        children: 'children'
                    }" @select="clickTreeNode"
                        style="margin-left: 5px;max-height: 100vh;overflow: auto;text-align: center !important;">
                        <template #title="{ name }">
                            <a-tooltip :content="name">
                                <div class="marquee">
                                    <icon-common />
                                    {{ name }}
                                </div>
                            </a-tooltip>
                        </template>
                    </a-tree>
                </div>

            </a-layout-sider>
            <a-layout-content>
                <a-card title="传感器详情">
                    <template #extra>
                        <a-button size="mini" type="primary" @click="goBack">返回</a-button>
                    </template>
                    <a-layout>
                        <a-layout>
                            <a-layout-content>
                                <div style="display: flex;">
                                    <div>
                                        数据图表
                                    </div>

                                    <div style="margin-left: 50px;">
                                        <a-radio-group v-model="position" type="button" @change="changeRadio">
                                            <a-radio value="0">1小时</a-radio>
                                            <a-radio value="1">1天</a-radio>
                                            <a-radio value="2">本月</a-radio>
                                            <a-radio value="3">上月</a-radio>
                                        </a-radio-group>
                                    </div>
                                </div>
                                <div id="mianchart" style="width: 100%;height: 350px;">

                                </div>
                            </a-layout-content>
                            <a-layout-sider style="min-width: 350px;">
                                <div style="margin-left: 50px;">
                                    <div>传感器信息</div>

                                    <div style="margin-top: 60px;">网关名称：{{ sensorInfo.node_name }}</div>
                                    <div style="margin-top: 10px;">传感器名称：{{ sensorInfo.name }}</div>
                                    <div style="margin-top: 10px;">传感器数值：{{ sensorInfo.sdata }}{{
                                        sensorInfo.data?.measure_unit_type
                                    }}</div>
                                    <div style="margin-top: 10px;">传感器类型：{{ sensorInfo.data?.iot_sensor_type }}</div>
                                </div>

                            </a-layout-sider>
                        </a-layout>
                        <a-layout-footer>
                            <a-table :data="tabList" row-key="id" :pagination="false">
                                <template #columns>
                                    <a-table-column title="名称">
                                        <template #cell="{ record }">
                                            {{ record.name }}
                                        </template>
                                    </a-table-column>
                                    <a-table-column title="关联传感器">
                                        <template #cell="{ record }">
                                            {{ (record.from_sensor_name) }}
                                        </template>
                                    </a-table-column>

                                    <a-table-column title="触发条件类型">
                                        <template #cell="{ record }">
                                            {{ record.data.iot_trigger_condition_type }}
                                        </template>
                                    </a-table-column>
                                    <a-table-column title="参数">
                                        <template #cell="{ record }">
                                            {{ record.condition_params }}
                                        </template>
                                    </a-table-column>


                                    <a-table-column title="循环间隔(s)">
                                        <template #cell="{ record }">
                                            {{ (record.trigger_inteval_time) }}
                                        </template>
                                    </a-table-column>

                                    <a-table-column title="状态">
                                        <template #cell="{ record }">
                                            <a-tag color="arcoblue" v-if="record.data.iot_trigger_status == '正常'">{{
                                                record.data.iot_trigger_status
                                            }}</a-tag>
                                            <a-tag color="red" v-else>{{ record.data.iot_trigger_status }}</a-tag>
                                        </template>
                                    </a-table-column>


                                    <a-table-column title="操作" align="center" fixed="right">
                                        <template #cell="{ record }">
                                            <a-space>
                                                <a-button type="primary" size="mini"
                                                    v-if="record.iot_trigger_status == 44" @click="kaiqi(record)">
                                                    <template #icon>
                                                        <icon-play-arrow-fill />
                                                    </template>
                                                    <!-- Use the default slot to avoid extra spaces -->
                                                    <template #default>开启</template>
                                                </a-button>
                                                <a-button type="primary" size="mini"
                                                    v-if="record.iot_trigger_status == 43" @click="zant(record)">
                                                    <template #icon>
                                                        <icon-pause-circle-fill />
                                                    </template>
                                                    <!-- Use the default slot to avoid extra spaces -->
                                                    <template #default>暂停</template>
                                                </a-button>

                                                <a-button size="mini" type="primary" status="danger"
                                                    @click="onDelete2(record)">删除</a-button>

                                            </a-space>
                                        </template>
                                    </a-table-column>
                                </template>
                            </a-table>
                        </a-layout-footer>
                    </a-layout>
                </a-card>
            </a-layout-content>
        </a-layout>
    </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { Modal, Message } from "@arco-design/web-vue";
import { gettriggerListAPI, deletetriggerAPI, updatetriggerAPI } from "@/api/modules/trigger/index";
import { getsensorListByIdAPI, getSensorhistory } from "@/api/modules/sensor/index";
import * as echarts from 'echarts';
const router = useRouter();
const route = useRoute();
const deviceLost = ref([])
const selId = ref(0) as any
const position = ref("")
import dayjs from 'dayjs';
// const defaultSelectedKeys = ref([]) as any
onMounted(() => {
    setFuzhi();
    selId.value = (route.query.id);
    getTrData();
    getTrData2();
    getTrData3();

})


const tabList = ref([])
async function getTrData() {
    let obj = {
        paged: 1,
        pageSize: 500
    }
    let obj2 = {
        from_sensor_id: selId.value
    }
    let res = await gettriggerListAPI(obj, obj2);
    tabList.value = []
    if (res.status == 2) {
        tabList.value = res.data.data
    }
}


const sensorInfo = ref({}) as any
async function getTrData2() {
    let res = await getsensorListByIdAPI(selId.value);
    if (res.status == 2) {
        sensorInfo.value = res.data
    }
}


const sensorInfohistory = ref({}) as any

const end_time = ref("")
const query_interval_type = ref(2)
const start_time = ref("")
async function getTrData3() {
    let obj = {
        sensor_id: selId.value
    }
    let res = await getSensorhistory(obj);
    sensorInfohistory.value = []
    if (res.status == 2) {
        sensorInfohistory.value = res.data.data
        flershData()
    }
}

async function changeRadio(val) {
    const today = dayjs();
    const last7Days = [];
    sensorInfohistory.value = []
    if (val == 1) {

        for (let i = 0; i < 2; i++) {
            const date = today.subtract(i, 'day').format('YYYY-MM-DD HH:mm:ss');
            last7Days.push(date);
        }
        const timeRange = ([last7Days[last7Days.length - 1], last7Days[0]])
        start_time.value = timeRange[0]
        end_time.value = timeRange[1]
        let obj = {
            sensor_id: selId.value,
            start_time: start_time.value,
            end_time: end_time.value,
            query_interval_type: query_interval_type.value
        }
        let res = await getSensorhistory(obj);
        if (res.status == 2) {
            sensorInfohistory.value = res.data.data

        } else {
            Message.info("该时间段暂无数据")
        }
        flershData()
    } else if (val == 0) {
        const now = dayjs();

        // 减去一个小时得到过去的时间点
        const oneHourAgo = now.subtract(1, 'hour');

        // 获取过去一个小时的开始时间（整点）
        const startOfOneHourAgo = oneHourAgo.startOf('hour');

        // 获取过去一个小时的结束时间（下一个整点的前一秒）
        // 方法一：使用 endOf('hour') 然后减去一秒（因为 endOf('hour') 实际上是下一个整点的开始时间，所以要减一秒）
        // 但注意，dayjs 的 endOf('hour') 直接返回的是下一个整点，所以我们需要稍微调整
        // const endOfOneHourAgoDirect = oneHourAgo.clone().endOf('hour').subtract(1, 'second');
        // 但这样有点绕，我们可以直接计算结束时间
        const endOfOneHourAgo = startOfOneHourAgo.add(1, 'hour').subtract(1, 'second');

        let obj = {
            sensor_id: selId.value,
            start_time: startOfOneHourAgo.format("YYYY-MM-DD HH:mm:ss"),
            end_time: endOfOneHourAgo.format("YYYY-MM-DD HH:mm:ss"),

        }
        let res = await getSensorhistory(obj);
        if (res.status == 2) {
            sensorInfohistory.value = res.data.data

        } else {
            Message.info("该时间段暂无数据")
        }
        flershData()

    } else if (val == 2) {
        // 获取当前时间
        const now = dayjs();

        // 获取过去30天的开始时间
        const startOfLast30Days = now.subtract(30, 'day').startOf('day');

        // 结束时间就是当前时间
        const endOfLast30Days = now;

        // 输出结果
        // console.log('过去30天的开始时间:', startOfLast30Days.format("YYYY-MM-DD HH:mm:ss"));
        // console.log('过去30天的结束时间（当前时间）:', endOfLast30Days.format("YYYY-MM-DD HH:mm:ss"));

        let obj = {
            sensor_id: selId.value,
            start_time: startOfLast30Days.format("YYYY-MM-DD HH:mm:ss"),
            end_time: endOfLast30Days.format("YYYY-MM-DD HH:mm:ss"),
            query_interval_type: 3
        }
        let res = await getSensorhistory(obj);
        if (res.status == 2) {
            sensorInfohistory.value = res.data.data

        } else {
            Message.info("该时间段暂无数据")
        }
        flershData()
    } else {
        // 获取当前时间
        const now = dayjs();

        // 获取上个月的开始时间（注意：这里可能会遇到月份天数的问题，但startOf('month')会自动处理）
        const startOfLastMonth = now.subtract(1, 'month').startOf('month');

        // 获取上个月的结束时间（即上个月的最后一天，23:59:59）
        const endOfLastMonth = startOfLastMonth.clone().endOf('month');

        // console.log('过去一个月的开始时间:', startOfLastMonth.format());
        // console.log('过去一个月的结束时间:', endOfLastMonth.format());
        let obj = {
            sensor_id: selId.value,
            start_time: startOfLastMonth.format("YYYY-MM-DD HH:mm:ss"),
            end_time: endOfLastMonth.format("YYYY-MM-DD HH:mm:ss"),
            query_interval_type: 3
        }
        let res = await getSensorhistory(obj);
        if (res.status == 2) {
            sensorInfohistory.value = res.data.data

        } else {
            Message.info("该时间段暂无数据")
        }
        flershData()
    }




}

async function kaiqi(val) {
    let obj = {
        id: val.id,
        iot_trigger_status: 43
    }
    let res = await updatetriggerAPI(obj);
    if (res.status == 2) {
        Message.success("操作成功")
    }
    getTrData();

}
async function zant(val) {
    let obj = {
        id: val.id,
        iot_trigger_status: 44
    }
    let res = await updatetriggerAPI(obj);
    if (res.status == 2) {
        Message.success("操作成功")
    }
    getTrData();
}

const onDelete2 = (row: any) => {
    Modal.warning({
        title: "提示",
        content: "确定删除？",
        hideCancel: false,
        closable: true,
        onOk: async () => {
            try {
                let res = (await deletetriggerAPI(row.id)) as any;
                if (res.status == 2) {
                    Message.success("删除成功");
                } else {
                    Message.error(res.statusMsg);
                }
                getTrData();
            } catch { }
        }
    });
};


function flershData() {
    let chartDom = document.getElementById('mianchart');
    let myChart = echarts.init(chartDom);
    let option;


    let date = [];
    let data = [];
    for (let i = 1; i < sensorInfohistory.value.length; i++) {

        date.push(sensorInfohistory.value[i].atimestr);
        data.push(sensorInfohistory.value[i].sdata);
    }
    option = {
        tooltip: {
            trigger: 'axis',
            position: function (pt) {
                return [pt[0], '10%'];
            }
        },
        title: {
            left: 'center',
            text: ''
        },
        toolbox: {
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                restore: {},
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: date
        },
        yAxis: {
            type: 'value',
            boundaryGap: [0, '100%']
        },
        dataZoom: [
            {
                type: 'inside',
                start: 0,
                end: 10
            },
            {
                start: 0,
                end: 10
            }
        ],
        series: [
            {
                name: sensorInfo.value.name,
                type: 'line',
                symbol: 'none',
                sampling: 'lttb',
                itemStyle: {
                    color: 'rgb(255, 70, 131)'
                },
                // areaStyle: {
                //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                //         {
                //             offset: 0,
                //             color: 'rgb(255, 158, 68)'
                //         },
                //         {
                //             offset: 1,
                //             color: 'rgb(255, 70, 131)'
                //         }
                //     ])
                // },
                data: data
            }
        ]
    };

    option && myChart.setOption(option);
}




function setFuzhi() {
    let userInfo = JSON.parse(localStorage.getItem("user-info") as string);
    deviceLost.value = userInfo.deviceListInfo

}

function clickTreeNode(val) {
    console.log(val);
    selId.value = val[0];
    getTrData();
    getTrData2();
    getTrData3();

}

function goBack() {
    router.back();
}
</script>

<style lang="scss" scoped>
.marquee {
    white-space: nowrap;
    /* 确保文本在一行内显示 */
    overflow: hidden;
    /* 隐藏溢出的内容 */
    text-overflow: ellipsis;
    /* 使用打点显示溢出的文本 */
    width: 100%;
    /* 设置宽度，根据需要调整 */
    max-width: 200px;
    /* 最大宽度，根据需要调整 */

    box-sizing: border-box;
    /* 防止宽度计算包含边框和内边距 */
}
</style>